<template>
  <div class="wrap">
    <section class="header">
      <div style="display: flex ;justify-content: space-between">
        <div style="min-width: 1360px">
          <ProductionSteps :active="9" :testFn="testFn" align-center/>
        </div>

        <div>
          <div
            style="display: flex;justify-content: flex-end;margin-right: 30px;padding-top: 10px"
          >
            <!--<transition name="el-fade-in">-->
            <!--<a-button-->
            <!--@click="printTest"-->
            <!--plain size="medium" style="margin-right: 10px" type="danger" v-if="isShowDev">-->
            <!--printTest-->
            <!--</a-button>-->
            <!--</transition>-->

            <el-popover
              placement="bottom"
              v-model="emptyProvVisible"
              width="200"
            >
              <p style="margin-bottom: 10px">请确认是否清空格子？</p>
              <div style="text-align: right; margin: 0">
                <el-button
                  :loading="loadingEmptyCellsBtn"
                  @click.stop="emptyCells"
                  size="mini"
                  type="danger"
                >确定
                </el-button>
                <el-button
                  @click="emptyProvVisible = false"
                  size="mini"
                  type="info"
                >取消
                </el-button>
              </div>
              <el-button slot="reference" type="primary">清空格子</el-button>
            </el-popover>
          </div>
        </div>
      </div>
    </section>

    <!--    <div>-->
    <!--                  <input type="file" name="main" id="main" value="" accept="image/png, image/jpeg, image/gif, image/jpg" @change="uploadImg($event)">-->
    <!--      <el-upload-->
    <!--        :before-upload="beforeUpload"-->
    <!--        :file-list="fileList"-->
    <!--        action="https://jsonplaceholder.typicode.com/posts/">-->
    <!--        <el-button size="small" type="primary">点击上传</el-button>-->
    <!--        <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>-->
    <!--      </el-upload>-->

    <!--    </div>-->

    <!--    <section class="help">-->
    <!--      <HeaderHelpDoc :head-context="headContext"/>-->
    <!--    </section>-->

    <el-row :gutter="20" class="main-wrap">
      <el-col :span="16">
        <div class="main-left">
          <el-row class="scan">
            <el-col class="operator-area">
            <span>
              <span
                style="padding-right: 30px;display: inline-block;position: relative;top: -5px;"
              >
                <span style="display: flex;flex-direction: column;">
                  <el-radio
                    :disabled="true"
                    label="0"
                    style="margin-bottom: 5px"
                    v-model="radio"
                  >单面直出</el-radio
                  >
                  <el-radio :disabled="true" label="1" v-model="radio"
                  >内页册</el-radio
                  >
                </span>
              </span>

              <span>
                <span style="padding-left: 30px">上一道工序:</span>
                <span style="padding: 15px">
                  <a-button @click="$router.push({ name: 'sorting' })"
                  >产品分拣</a-button
                  >
                </span>
              </span>

              <span>
                <!-- scanBarcodeHandle -->
                <span>请扫描SN条码: </span>
                <el-input
                  @keydown.native.enter="scanBarcodeHandle"
                  clearable
                  placeholder="点击此处开始扫描"
                  style="width: 200px"
                  v-loading="loadingSearch"
                  v-model.trim="searchInput"
                />
                <!--                <a-button @click="testPrint">test use</a-button>-->
              </span>

              <template v-if="isDirectOutput">
                <transition name="el-fade-in">
                  <span style="margin-left: 15px">
                    <span>包裹重量: </span>
                    <el-input
                      :disabled="true"
                      :value="packageWeight"
                      style="width: 110px"
                    >
                      <template slot="append"
                      >kg</template
                      >
                    </el-input>
                  </span>
                </transition>
              </template>
            </span>
            </el-col>

            <el-col class="condition-filter">
              <el-input
                class="azure-scan-bag-code"
                clearable
                placeholder="请输入内容"
                style="width: 300px"
                suffix-icon="el-icon-search"
                v-model="scanBarcode"
              >
              </el-input>
              <line-select
                :value.sync="selectedLineBody"
                @clear="clearSelect"
                style="margin-left: 30px;width: 230px"
              />
            </el-col>

            <el-col class="show-work-sit">
              <work-sit-info :workStationData="workStationData" title="信息展示">
                <template #more>
                  <el-row style="padding-top: 20px">
                    <el-col :span="6">
                      <span>是否包邮：</span>
                      <span>未知</span>
                    </el-col>
                    <el-col :span="6">
                      <span>付费方式：</span>
                      <span>{{ shipmentData.FreightPayTypeDisplay }}</span>
                    </el-col>
                    <el-col :span="6">
                      <span>运输方式：</span>
                      <span>{{
                      shipmentData.ShippingBy === 112
                        ? '空运'
                        : [154, 0].includes(shipmentData.ShippingBy)
                        ? '陆运'
                        : '未知运输方式'
                    }}</span>
                    </el-col>
                    <el-col :span="6">
                      <span>快递公司：</span>
                      <span>{{ shipmentData.ShippingCompanyName }}</span>
                    </el-col>
                  </el-row>

                  <el-row style="padding-top: 20px">
                    <el-col :span="6">
                      <span>客户名称：</span>
                      <span>{{ shipmentData.ShopName }}</span>
                    </el-col>
                    <el-col :span="6">
                      <span>包装箱最大数量：</span>
                      <span>未知</span>
                    </el-col>
                  </el-row>
                </template>
              </work-sit-info>
            </el-col>

            <el-col style="padding: 10px">
              <el-alert
                :closable="false"
                :title="
                `当前为(${ShippingByType[shipmentData['ShippingBy']]})发货`
              "
                show-icon
                type="success"
                v-show="Object.keys(shipmentData).length > 0"
              >
              </el-alert>
            </el-col>

            <el-col class="album-grid">
              <!--       单面直出和内页册不同的排版,单面直出需要分组显示    -->
              <div class="album-grid-wrap">
                <!--     每一组分为一个row(根据订单来分)  根据row来for循环  -->
                <transition mode="out-in" name="el-fade-in">
                  <component
                    ref="cell-list"
                    v-bind="singerOrInner"
                    v-loading="loadingCellList"
                  />
                </transition>
              </div>
            </el-col>

            <!--     -->
            <template>
              <!--     buttons   目前要来统一改为获取,并且打印       -->
              <!--       现在空运和陆运都在这里打印 ShippingBagsForLand     -->
              <!--       v-if="shipmentData.ShippingBy === 112"     -->
              <el-col>
                <el-card style="display: flex;justify-content: flex-end">
                  <el-button :loading="doingPrintAll" @click="ShippingAviation" type="primary"
                  >打印全部条码
                  </el-button>
                </el-card>
              </el-col>

              <!--     快递区域     -->
              <!--            <el-col style="margin-top: 30px">-->
              <!--              <el-card>-->
              <!--                <div class="clearfix" slot="header">-->
              <!--                  <span>快递信息</span>-->
              <!--                </div>-->

              <!--                <span style="margin-left: 15px">-->
              <!--                <span>打印快递单: </span>-->
              <!--                 <el-input-->
              <!--                   @keydown.native.enter="scanExpressBarcodeHandle"-->
              <!--                   clearable placeholder="点击此处开始扫描快递单"-->
              <!--                   style="width: 310px"-->
              <!--                   v-loading="loadingExpress"-->
              <!--                   v-model.trim="expressInput">-->
              <!--                 </el-input>-->

              <!--             </span>-->
              <!--              </el-card>-->
              <!--            </el-col>-->
            </template>
          </el-row>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="main-right">
          <el-tabs type="border-card">
            <el-tab-pane
              class="azure-panel"
              label="订单信息"
              ref="better-wrapper"
            >
              <div>
                <div
                  style="margin: 30px 0"
                  v-for="(trade, idx) in unCompleteOrderData"
                >
                  <section style="display: flex;justify-content: space-between">
                    <h3 style="margin-bottom: 5px">
                      订单号:{{ trade.NetOrderId }}
                    </h3>
                    <h3 style="margin-bottom: 5px">订单状态: ???</h3>
                  </section>
                  <section>
                    <h3 style="margin-bottom: 5px">客户名称:{{ trade.Name }}</h3>
                  </section>
                  <azure-dynamic-table
                    :column-des-objs="columnDesObjs"
                    :data="trade.OrderProductVos"
                  />
                  <el-divider v-if="unCompleteOrderData.length - 1 !== idx"/>
                </div>
              </div>

              <!--            <azure-dynamic-table :column-des-objs="columnDesObjs" :data="tableData"/>-->
            </el-tab-pane>

            <el-tab-pane label="作业指导书" name="direction">
              作业指导书 ... (待完中)
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-col>
    </el-row>

  </div>
</template>

<script>
  import ProductionSteps from '@/views/productManagement/aComponents/ProductionSteps'
  import HeaderHelpDoc from '@/components/ATheFridayClub/HeaderHelpDoc'
  import AButton from '@/components/ATheFridayClub/AButton'
  import LineSelect from '@/components/ATheFridayClub/businessRelation/LineSelect'
  import WorkSitInfo from '@/components/ATheFridayClub/businessRelation/WorkSitInfo'
  import {
    AddPackageBag,
    DeleteShippingRecord,
    GetShippingRecord,
    GetUnCompleteOrder,
    Shipping,
    ShippingAutoComputeWeight,
    ShippingBagsForLand
  } from '@/api/factoryPresetScan'
  import AzureDynamicTable from '@/components/ATheFridayClub/mDynamicTable/AzureDynamicTable'
  import {ERR_OK, printPdf} from '@/utils/commons'
  import _ from 'lodash'
  import lineBodyRelate from '@/mixins/lineBodyRelate'
  import DirectOutputPackConsignment from '@/views/productManagement/aComponents/DirectOutputPackConsignment'
  import InsideVolumePackingConsignment from '@/views/productManagement/aComponents/InsideVolumePackingConsignment'

  import Vue from 'vue'
  import {getLodop} from '@/views/productManagement/assets/LodopFuncs'
  import devFunc from '@/mixins/devFunc'
  //  打包发货,内页册和单面直出
  import BScroll from '@better-scroll/core'

  const RType = {
    0: '直出',
    1: '内页册'
  };

  // ShippingBy => 112 空配，154 陆运

  const ShippingByType = {
    112: '空配',
    154: '陆运'
  };

  const tabNames = {
    direction: 'direction',
    orderInfos: 'orderInfos'
  };

  const DEFAULT_VALUE = -1; //  默认值传0,.net不允许不传

  //  考虑到空运和陆运
  export default {
    name: 'shipments',
    components: {
      InsideVolumePackingConsignment,
      DirectOutputPackConsignment,
      AzureDynamicTable,
      WorkSitInfo,
      LineSelect,
      AButton,
      HeaderHelpDoc,
      ProductionSteps
    },
    mixins: [lineBodyRelate, devFunc],
    provide() {
      return {
        shipmentIns: this //  或者 bind this (不推荐)
      }
    },
    $_techType: 9, //  线体使用,放在options中保险一些,这样不会污染data

    data() {
      this.ShippingByType = ShippingByType;
      return {
        tabsName: tabNames.direction,
        // groupByOrderCode: {},
        // techType: 6, //  线体使用
        selectedLineBody: '', //  线体使用,用户选择的线体

        headContext: '包装发货分为内页册页和单面直出.',

        scanBarcode: '', //  用户扫描或输入的条形码
        searchInput: '',
        loadingSearch: false,

        workStationData: {}, //  工位的信息
        tableData: [],

        //  未完成的订单
        columnDesObjs: [
          {key: 'OrderProductCode', label: 'SN条形码', width: '160'},
          {key: 'Name', label: '产品名称', width: '130'},
          {key: 'Spec', label: '规格', tag: true},
          {key: 'PhotoNum', label: '数量'},
          {key: 'TechName', label: '当前状态', tag: true},
          {key: 'TechTime', label: '更新时间', width: '160'}
        ],

        scanBarcodeArr: [], //  长度只能为 2
        loadingScan: false,
        loadingEmptyCellsBtn: false,
        emptyProvVisible: false,

        // cellList: [], //  格子数据

        loadingCellList: false,
        shipmentData: {},

        // times: 0, //  距离上次查询的次数
        lastGetUnCompleteOrderDate: null, //  上次查询未完成订单的时间
        unCompleteOrderData: [],

        // packageWeight: 0

        loadingExpress: false,
        expressInput: '',
        scroll: null,
        doingPrintAll: false
      }
    },
    watch: {
      // unCompleteOrderData: {
      //   deep: true,
      //   handler(val) {
      //     console.log(val)
      //     console.log('scroll ~~~~~~~~~~~~~~~~')
      //     console.log(this.scroll)
      //     this.$nextTick(() => {
      //       this.scroll.refresh()
      //     })
      //   }
      // }
    },
    computed: {
      radio: {
        get() {
          const {RType} = this.shipmentData;
          return RType ? RType.toString() : '-1'
        }
      },
      packageWeight: {
        get() {
          const {ShippingBagOvs} = this.shipmentData;
          if (ShippingBagOvs && ShippingBagOvs.length) {
            return _.head(ShippingBagOvs) ? _.head(ShippingBagOvs)['Weight'] : 0
          }
          return 0
        }
      },
      isDirectOutput() {
        return this.shipmentData ? +this.shipmentData['ShippingBy'] === 112 : ''
      },
      //  绑定组件,根据内页册还是单面直出显示
      singerOrInner() {
        return {
          is: this.isDirectOutput
            ? 'DirectOutputPackConsignment'
            : 'InsideVolumePackingConsignment',
          shipmentData: this.shipmentData
          // groupByOrderCode: this.groupByOrderCode
        }
      },
      cellListRef() {
        return this.$refs['cell-list']
      }
    },
    mounted() {
      const {
        $refs: {['better-wrapper']: wrap}
      } = this;
      let scroll;
      this.$nextTick(() => {
        scroll = this.scroll = new BScroll(wrap.$el, {
          scrollY: true,
          scrollbar: {
            fade: false,
            interactive: true
          },
          mouseWheel: {
            speed: 20,
            invert: false,
            easeTime: 300
          }
        })
      });

      this.$watch(
        'unCompleteOrderData',
        async () => {
          await this.$nextTick();
          scroll && typeof scroll.refresh === 'function' && scroll.refresh()
        },
        {deep: true}
      )
    },
    methods: {
      testFn(key) {
        console.log(this.$options.name);
        console.log(key);
        return new Promise(resolve => {
          setTimeout(() => {
            resolve(333)
          })
        })
      },

      //  空运发货,批量打印空运快递单
      async ShippingAviation() {
        try {
          this.doingPrintAll = true;
          //  如果没有选择线体,不允许打印订单,因为会使用默认打印机
          const {PrinterName} = this.workStationData;
          if (!PrinterName) {
            this.$message.warning('没有选择线体,请选择线体之后打印');
            return
          }

          const {
            ShippingId,
            ShippingBagOvs = [],
            ShippingBy
          } = this.shipmentData;
          const isAir = ShippingBy === 112;
          //  154 ShippingBagsForLand
          const {Result, Code, Message} = await (isAir
            ? ShippingAutoComputeWeight
            : ShippingBagsForLand)(
            (() => {
              return isAir
                ? {shippingid: ShippingId}
                : ShippingBagOvs.map(({Weight, Code}) => ({Weight, Code}))
            })()
          );

          if (+Code === 1) {
            Result.forEach(({ReportList = []}) => {
              ReportList.filter(v => v).forEach(({Context, PrinterName}) => {
                console.log('ShippingAutoComputeWeight || ShippingBagsForLand => printPdf params => %o', ReportList);
                printPdf(Context, PrinterName)
              })
            });

            this.$message.success(`打印成功:${Message}`);
            if (!isAir) {
              this.shipmentData.ShippingBagOvs = []  //  发货完成清空格子信息
            }
          }
        } catch (e) {
          console.log(e);
          const {Result, Code, Message} = e;
          this.$message.error(`打印失败:${Message}`)
        } finally {
          this.doingPrintAll = false
        }

        //   const { ShippingId } = this.shipmentData;
        //   const { Result, Code, Message } = await ShippingAutoComputeWeight({
        //     shippingid: ShippingId
        //   });
        //   if (+Code === 1) {
        //     //  ShippingBagOvs
        //     this.CreateOneFormPages(
        //       Result.map(({ ShippingReport }) => ShippingReport)
        //     );
        //     this.$message.success(`打印成功:${Message}`);
        //   }
        // } catch (e) {
        //   console.log(e);
        //   const { Result, Code, Message } = e;
        //   this.$message.error(`打印失败:${Message}`);
        // } finally {
        // }
      },

      // printTest() {
      //   const LODOP = getLodop()
      //   LODOP['SET_PRINT_PAGESIZE'](1, '100mm', '130mm')
      //   import('./pdfStream').then(({ stream }) => {
      //     LODOP['ADD_PRINT_PDF'](0, 0, '100%', '100%', stream)
      //     LODOP['PREVIEWB']()
      //   })
      // },

      //  批量打印
      /**
       * @deprecated
       */
      CreateOneFormPages(contents) {
        try {
          const LODOP = getLodop();
          const {PrinterName} = this.workStationData;
          console.log(PrinterName);
          for (const content of contents) {
            LODOP['SET_PRINT_PAGESIZE'](1, '100mm', '130mm');
            LODOP['ADD_PRINT_PDF']('2mm', 0, '100%', '100%', content);
            LODOP['SET_PRINTER_INDEX'](PrinterName);
            LODOP.PRINT()
          }
        } catch (e) {
          this.$notify({
            title: '没有找到打印服务',
            message: this.$createElement(
              'div',
              {style: 'color: #ffffff'},
              '确认打印服务已经被正确安装.'
            ),
            duration: 0,
            type: 'warning'
          })
        }
      },

      //  模板上来选择调用不同的方法
      async scanLand(params) {
        console.log('scan land');
        console.log(this.cellListRef.$data);
        let {curSelBag} = this.cellListRef.$data; //  用户当前选中的包裹

        console.log(curSelBag, 595);
        const {ShippingNo} = this.shipmentData;

        const {BagOrder} = await this.createdBag(ShippingNo); //  自动调用创建包裹接口... 并返回创建的order

        // const newBagIdx = this.cellListRef.$data.shipmentData.ShippingBagOvs.length
        //  curSelBag 不在取 0 - n ,而是取服务端的,保险一些
        Object.assign(params, {
          packageBagOrder:
            curSelBag === -1 ? BagOrder : this.cellListRef.getCurSelBagOrder()
        });
        // params.packageBagOrder = curSelBag === -1 ? BagOrder : curSelBag //  用户一个没选,就认为是创建了包裹,使用刚刚创建出来的包裹号

        console.log(params);
        //  依旧还是把用户扫描的code给传入
        //  只有首次调用时才刷新
        console.log('BagOrder', BagOrder);

        //  每次还是重新赋值,因为服务端给予了最新的数据
        await this.shipping(params, {notOverRideData: false})
      },

      //创建包裹
      async createdBag(ShippingNo) {
        let {curSelBag} = this.cellListRef.$data; //  用户当前选中的包裹
        console.log(curSelBag);

        //  直接添加进入原包裹,不调用添加的接口
        if (curSelBag > -1) {
          return Promise.resolve({})
        }

        const {Result, Code} = await AddPackageBag({ShippingNo});
        if (+Code === ERR_OK) {
          //  把包裹的数据添加,因为重新请求scan接口是没有用的  Result

          //  OP0000004069 OP0000004070
          console.log('添加包裹成功');
          console.log(Result);
          this.shipmentData.ShippingBagOvs = [
            ...this.shipmentData.ShippingBagOvs,
            Result
          ];

          this.$_setInsideState(this.shipmentData);
          console.log(this.shipmentData.ShippingBagOvs);

          // const {Result: res, Code} = await GetShippingBag({
          //   shippingBagCode: ShippingNo,
          //   isGetAll: true
          // });

          // this.cellListRef.focus(curSelBag + 1) //  成功的情况才focus最新的一个
          await this.$nextTick();
          this.cellListRef.focusLast(); //  成功的情况才focus最新的一个

          this.$message.success('创建包裹成功.');
          return Promise.resolve(Result)
        }
      },
      async testPrint() {
        const {default: data} = await import('./pdfData/index');
        printPdf(data, '', (TaskID, Value) => {
          // console.log('do print task')
          console.log(TaskID, Value)
        })
      },
      /**
       * 用户扫描条码
       */
      async scanBarcodeHandle(e) {
        try {
          const {value: code} = e.target;
          const params = {code: code};

          if (params.code === '') {
            this.$message.warning('条码不能为空!');
            return
          }

          //  获取未完成订单列表的数据
          //  获取未完成订单的异常无关紧要,由内部捕获
          this.getUnCompleteOrder({code}).catch(e => {
            console.log(e);
            this.$message.warning('获取未完成的订单失败!😂😂')
          });

          //  第一次扫描,初始化
          if (Object.keys(this.shipmentData).length === 0) {
            Object.assign(params, {packageBagOrder: DEFAULT_VALUE});
            const type = await this.shipping(params);

            //  OP0000004069 OP0000004070
            console.log('如果是内页册');
            console.log(type);
            //  如果是内页册,默认选择第一个focus
            if ([154, 0].includes(type)) {
              //  内页册   ,陆运
              this.cellListRef.focusLast();
              return
            }
            return
          }

          const {RType, ShippingBy} = this.shipmentData;
          //  第二次和之后的扫描 有数据的情况
          if (ShippingBy === 112) {
            //   直出  空运
            Object.assign(params, {packageBagOrder: DEFAULT_VALUE});
            await this.shipping(params)
          } else if ([154, 0].includes(ShippingBy)) {
            //  内页册 陆运
            console.log('陆运~~~');
            await this.scanLand(params)
          }
        } catch (e) {
          console.log(e)
        } finally {
          //  清空用户输入
          this.searchInput = ''
        }
      },

      /**
       *  用户扫码调用,初始化数据
       */
      async shipping(params, {notOverRideData = false} = {}) {
        const {Code, Result, Message, ErrorCode} = await Shipping(params);
        this.$message[+Code === 1 ? 'success' : 'error'](Message);
        //  可能已经发过了货 106 , 临时修改
        if ('-106' === ErrorCode) {
          this.$confirm('该陆运包裹已经打印发货,是否重新打印?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              GetShippingRecord({code: params.code}).then(
                ({Result, Code, Message}) => {
                  //  { ShippingReport }

                  // const ShippingReportList = Result.map(
                  //   ({ ShippingReport }) => ShippingReport
                  // )

                  // this.CreateOneFormPages(ShippingReportList)
                  // Result.map(({ ShippingReport }) => ShippingReport)

                  Result.forEach(({ReportList = []}) => {
                    ReportList.filter(v => v).forEach(({Context, PrinterName}) => {
                      console.log('GetShippingRecord => printPdf params => %o', ReportList);
                      printPdf(Context, PrinterName)
                    })
                  });

                  this.$message({
                    type: 'success',
                    message: '重新发货成功!'
                  })
                  // this.CreateOneFormPages(Array.of(ShippingReport))
                }
              )
              //  code
            })
            .catch(e => {
              console.log(e)
            })
        }

        if (notOverRideData) return;

        if (+Code === 1) {
          this.shipmentData = Result || {}; //  把包裹信息设置,并返回
          //  单面直出里面加合并按钮
          if (this.isDirectOutput) {
            //  单输出 空运
            //  重新组织单面直出数据结构,分组
            this.shipmentData.groupByOrderCode = this.$_groupByOrderCode(
              this.shipmentData.ShippingBagOvs
            );
            this.$_setBagsMergeProperties(this.shipmentData.groupByOrderCode)
          } else {
            this.$_setInsideState(this.shipmentData)
          }
          return this.shipmentData['ShippingBy']
        }

        return Result
      },

      async paramsConstructor(params) {
        //  传值参数的处理
        Object.assign(params, {
          //  1 首先判断是内页册还是单面直出
          packageBagOrder: await (async () => {
            if (!this.isDirectOutput) {
              //  内页册 陆运
              //  取到用户当前点击的那一个包的编号

              // 内页册    获取到子组件中
              //  如果内页册中选择的curSel不为 -1 那就取他,否则取默认值
              await this.$nextTick();
              //  ???
              const {curSelBag} = this.$refs['cell-list'].$data;
              return curSelBag ? curSelBag : DEFAULT_VALUE
            }
            //  单输出 空运
            return DEFAULT_VALUE
          })()
        })
      },

      /**
       * 单面印和双面印都是调用这个接口 ??? 这样不太好
       * @param code 是  string  产品\组件\照片编码
       * @param packageBagOrder 否  int  追加产品时的包裹序号
       */
      async shippingController({code, packageBagOrder} = {}) {
        try {
          this.loadingSearch = true;

          //  内页册重货包裹,且当前没有被选中的包裹时才会创建包裹

          await this.createLandBag(); //  先创建包裹

          const {Code, Result} = await Shipping({code, packageBagOrder});

          if (+Code === 1) {
            this.shipmentData = Result; //  把包裹信息设置,并返回
            //  单面直出里面加合并按钮
            if (this.isDirectOutput) {
              //  单输出 空运
              //  重新组织单面直出数据结构,分组
              this.shipmentData.groupByOrderCode = this.$_groupByOrderCode(
                this.shipmentData.ShippingBagOvs
              );
              this.$_setBagsMergeProperties(this.shipmentData.groupByOrderCode)
            } else {
              this.$_setInsideState(this.shipmentData)
            }
            this.$message.success('更新包裹信息成功.');
            return true
          }
        } catch (e) {
          console.log(e);
          return new Error(e)
        } finally {
          this.loadingSearch = false; //  是否加载 ?
          this.searchInput = '' //  清空用户输入的,方便下次直接扫码
        }
      },
      //  内页册的包裹中设置参数
      $_setInsideState(shipmentData) {
        console.log(shipmentData);
        if (Object.keys(shipmentData).length === 0) {
          return
        }
        shipmentData.ShippingBagOvs.forEach((cell, idx, arr) => {
          if (!Reflect.has(cell, 'isWeighing')) {
            this.$set(cell, 'isWeighing', false)
          }
          //陆运添加isMerge属性
          // if (!Reflect.has(cell, "isMerge")) {
          //   //  定义响应式对象
          //   this.$set(cell, "isMerge", false);
          // }
          if (arr.length - 1 === idx) {
            if (!Reflect.has(cell, 'isMerge')) {
              //  定义响应式对象
              this.$set(cell, 'isMerge', false)
            }
          }
        })
      },
      update() {
        if (this.isDirectOutput) {
          this.$_setBagsMergeProperties(this.shipmentData.groupByOrderCode)
        } else {
          //添加陆运
          this.$_setInsideState(this.shipmentData)
        }
      },
      //  给属性设置isMerge属性
      $_setBagsMergeProperties(groupByOrderCode) {
        Object.values(groupByOrderCode).forEach(group => {
          group.forEach((e, idx, arr) => {
            // console.log(e.ShoShippingBagDetailVos);
            e.ShoShippingBagDetailVos.forEach(prod => {
              //  每一个产品 isEdit 都会添加
              this.$set(prod, 'isEdit', false)
            });

            if (arr.length - 1 === idx) {
              if (!Reflect.has(e, 'isMerge')) {
                //  定义响应式对象
                this.$set(e, 'isMerge', false)
              }
            }
          })
        })
      },
      //  把箱包根据订单号来进行分组 OP0000004140
      $_groupByOrderCode(bagCells) {
        return Vue.observable(
          bagCells
            ? bagCells.reduce((acc, cur) => {
              const {OrderBagId: OrderCode} = cur;
              if (!Reflect.has(acc, OrderCode)) {
                // OrderCode in acc
                this.$set(acc, OrderCode, [])
              }
              acc[OrderCode].push(cur);
              return acc
            }, {})
            : Object.create(null)
        )
      },
      //  清空全部的格子
      async emptyCells() {
        try {
          this.loadingEmptyCellsBtn = true;

          console.log(this.shipmentData.ShippingId);
          if (!this.shipmentData.ShippingId) {
            this.$notify({
              title: '当前格子为空不需要清空',
              type: 'info'
            });
            return
          }

          const {Code, Messsage, Result} = await DeleteShippingRecord({
            shippingid: this.shipmentData.ShippingId
          });

          if (+Code === ERR_OK) {
            this.$message.success('清空格子成功!');
            this.shipmentData = {};
            this.emptyProvVisible = false
          }
          console.log('~~~~\'~\'~~~~~~~~~~')
        } catch (e) {
          console.log(e)
          // this.emptyProvVisible = false;
        } finally {
          setTimeout(() => {
            this.loadingEmptyCellsBtn = false
          }, 1000)
        }
      },
      //  历史波次查询
      historyQuery() {
      },
      /**
       * 清空线体选择
       */
      clearSelect() {
        this.workStationData = {}
      },
      //  快递单扫描
      scanExpressBarcodeHandle() {
      },
      /**
       *  获取右边表格的数据
       */
      // async getUnCompleteOrder({ code }) {
      //   console.log('isNeedRefreshData~~~')
      //   // console.log(this.isNeedRefreshData())
      //   if (!this.isNeedRefreshData()) {
      //     return
      //   }
      //   console.log('getData')
      //   try {
      //     //  code	是	string	产品\组件\照片编码
      //     // const { default: res } = await import('./mockUnCompleteOrder.js')
      //     // const { Code, Result } = res
      //     const { Code, Result } = await GetUnCompleteOrder({ code })
      //     if (+Code === 1) {
      //       return (this.unCompleteOrderData = Result)
      //     }
      //   } catch (e) {
      //     return new Error(e)
      //   } finally {
      //     //  获取完成之后更新上次获取的时间并记录
      //     this.lastGetUnCompleteOrderDate = new Date().getTime()
      //   }
      // },
      getCurPage() {
        const {curSelBag} = this.$refs['cell-list'].$data;
        return curSelBag
      },

      /**
       *  上次的数据是否过期
       *  @return true => 需要刷新   ,   false => 不需要刷新
       */
      isNeedRefreshData() {
        const expireTime = 60 * 10 * 1000; //  10分钟获取一次数据,距离第一次请求
        if (!this.lastGetUnCompleteOrderDate) {
          //  第一次进入是没有上次访问的时间的,
          //  这时只需要记录一下,并且返回需要刷新即可
          this.lastGetUnCompleteOrderDate = new Date().getTime();
          return true
        }
        const now = new Date().getTime();
        const isTimeExpired = now - this.lastGetUnCompleteOrderDate > expireTime;
        console.log((now - this.lastGetUnCompleteOrderDate) / 1000);
        return isTimeExpired
      },

      /**
       *  获取右边表格的数据
       */
      async getUnCompleteOrder({code}) {
        console.log('isNeedRefreshData~~~');
        // console.log(this.isNeedRefreshData())
        if (!this.isNeedRefreshData()) {
          return
        }
        console.log('getData');
        try {
          //  code	是	string	产品\组件\照片编码
          // const { default: res } = await import('./mockUnCompleteOrder.js')
          // const { Code, Result } = res
          const {Code, Result} = await GetUnCompleteOrder({code});
          if (+Code === 1) {
            this.tabsName = tabNames.orderInfos;
            return (this.unCompleteOrderData = Result)
          }
        } catch (e) {
          return new Error(e)
        } finally {
          //  获取完成之后更新上次获取的时间并记录
          this.lastGetUnCompleteOrderDate = new Date().getTime()
        }
      },
      //  如果满足没有被选中,并且不是第一次请求接口的情况,调用创建陆运包裹
      async createLandBag() {
        if (+this.shipmentData['RType'] === 1 && this.getCurPage() === -1) {
          //  1 内页册
          //  auto create bag  =>  land express
          //  如果内页册的页面,且没有被选中,且第一次获取数据,这时才去向服务端请求数据来自动创建包裹
          await this.$nextTick();
          console.log(this.$refs['cell-list'].$data, 874);
          const {curSelBag} = this.$refs['cell-list'].$data; //  获取当前选择的包裹
          const curHasData = !!this.shipmentData.ShippingBagOvs; //  当前是否已经请求过了
          //  当前没有被选择的 并且 当前已经有数据了 才会调用新增包裹
          if (curSelBag < 0 && curHasData) {
            //  当前没有被选中的内页册包裹,所以直接创建
            const {ShippingNo} = this.shipmentData;
            //  调用新增接口创建
            const {Result, Code} = await AddPackageBag({ShippingNo});
            if (+Code === ERR_OK) {
              this.$message.success('创建包裹成功.');

              //  创建完成包裹之后把curIdx更改为当前length+1
              this.$refs[
                'cell-list'
                ].$data.curSelBag = this.shipmentData.ShippingBagOvs.length

              //  ...... todo 把返回的数据重新插入,其实不用插入,因为之后会call scan api
              //  不需要重新指向新插入的数据,都是灰色的,只有再次添加的时候才会亮
            }
          }
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  @import "~@/styles/index.scss";

  /deep/ .bag-wrap {
    div:first-child {
      display: flex;
      justify-content: center;
    }
  }

  .wrap {
    .header {
      padding: 10px 0;
    }

    .help {
      padding: 10px;
    }

    .main-wrap {
      padding: 10px;
      font-size: $mainSize;

      .main-left {
        margin-right: 15px;
        margin-left: 10px;

        .scan {
          .operator-area {
            padding: 15px 10px;
            border: 1px solid $borderColor;
            border-radius: 3px;
          }

          .condition-filter {
            /*margin: 30px 0;*/
            padding: 30px 0;
          }

          .album-grid {
            width: 100%;

            .album-grid-wrap {
              padding: 30px 0;
            }
          }
        }
      }

      .main-right {
        /*min-width: 970px;*/
        margin-right: 10px;

        .azure-panel {
          height: 700px;
          overflow: hidden;
        }
      }
    }
  }
</style>
